package com.huiying.controller;


import com.huiying.constant.JwtClaimsConstant;
import com.huiying.entity.dto.UserDTO;
import com.huiying.entity.entity.User;
import com.huiying.entity.result.Result;
import com.huiying.entity.vo.FollowVO;
import com.huiying.entity.vo.UserLoginVO;
import com.huiying.entity.vo.UserVO;
import com.huiying.properties.JwtProperties;
import com.huiying.service.UserService;
import com.huiying.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lsh
 * @Date: 2024/10/25/21:23
 * @Description: 用户登录
 */
@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;


    /***
     * 微信用户登录
     * @param: code 前端返回code
     * @return: com.fx.result.Result<com.fx.vo.UserLoginVO>
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody Map<String, String> request) {
        String code = request.get("code"); // 从 JSON 对象中获取 code
        log.info("收到登录请求，code: {}", code);

        // 调用用户服务进行登录
        User user = userService.login(code);

        // 为微信用户生成 jwt 令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        String redisKey = "user:token:"+user.getId();
        redisTemplate.opsForValue().set(redisKey,token,jwtProperties.getUserTtl(), TimeUnit.SECONDS);
        // 判断是否首次登录
        String isFirst = "1";
        if (StringUtils.isBlank(user.getUsername())) { // 使用 StringUtils 判断
            isFirst = "1"; // 用户名为空或者仅为空格，表示首次登录
        } else {
            isFirst = "0"; // 用户名已存在，非首次登录
        }

        // 构建返回对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .avatar(user.getAvatar())
                .isFirst(isFirst)
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }


    /***
     * 根据id查询用户信息
     * @param id 路径参数，用户id
     * @return: com.fx.result.Result
     */
    @ApiOperation("根据id查询用户信息")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id){
        log.info("根据id查询用户信息");
        UserVO user = userService.getById(id);
        return Result.success(user);
    }

    /***
     * 修改用户信息
     * @param userDTO 新的用户信息
     * @return: com.fx.result.Result
     */
    @PutMapping("/update")
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody UserDTO userDTO){
        log.info("修改用户信息");
        userService.update(userDTO);
        return Result.success();
    }

    /**
     *  获取关注列表
     * @return: com.fx.result.Result<java.util.List<com.fx.vo.FollowVO>>
     */
    @ApiOperation("查询用户列表")
    @GetMapping("/followeeList")
    public Result<List<FollowVO>> list(){
        log.info("查询用户关注列表");
        List<FollowVO> followeeList = userService.list();
        return Result.success(followeeList);
    }

    @ApiOperation("查询用户粉丝列表")
    @GetMapping("/fansList")
    public Result<List<FollowVO>> fansList(){
        log.info("查询用户粉丝列表");
        List<FollowVO> fansList = userService.fansList();
        return Result.success(fansList);
    }


    /***
     * 添加关注对象
     * @param followeeId 被关注者id
     * @return: com.fx.result.Result
     */
    @ApiOperation("添加关注")
    @PutMapping("/follow")
    public Result follow(Long followeeId){
        log.info("关注用户:{}",followeeId);
        userService.follow(followeeId);
        return Result.success();
    }

    /**
     * 取消关注
     * @param followeeId 被关注id
     * @return: com.fx.result.Result
     */
    @ApiOperation("取消关注")
    @DeleteMapping("/unfollow")
    public Result unfollow(Long followeeId){
        log.info("取消关注:{}",followeeId);
        userService.unfollow(followeeId);
        return Result.success();
    }
}
